use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use chrono::Local;
use yew::{function_component, html, use_context, Callback, Html, Properties};
use yew::platform::spawn_local;
use yew_hooks::use_local_storage;
use yew_router::hooks::use_navigator;
use yewdux::use_dispatch;
use crate::business::app_state::AppState;
use crate::business::page::fragment::im_session_list_view::{SessionAction, SessionListState};
use crate::business::service::message_send_service::MessageSendService;
use crate::business::share::dto::RefMessageData;
use crate::business::util::css::{add_class, remove_class};
use crate::business::util::input::{get_textarea_value, set_textarea_value};
use crate::business::util::local_seq::local_seq;
use crate::business::util::util::{get_login_info, to_login};
use crate::db::pojo::pojo::{ImMessage, ImSession};

#[derive(Properties, PartialEq, Clone)]
pub struct MessageEditorViewProps {
    pub session: Option<Rc<RefCell<ImSession>>>,
    pub ref_message: Option<RefMessageData>,
    pub show_message_callback: Callback<Vec<ImMessage>>,
}

#[function_component(MessageEditorView)]
pub fn message_editor_view(props: &MessageEditorViewProps) -> Html{
    let app_state = use_context::<AppState>().unwrap();

    let local_storage = use_local_storage::<String>("_login_".to_string());
    let user_id = match get_login_info(local_storage) {
        None => {None}
        Some(token) => {
            Some(token.use_id)
        }
    };

    let navigator = use_navigator().unwrap();

    let app_state_clone = app_state.clone();
    let session_clone = props.session.clone();
    let user_id_clone = user_id.clone();
    let ref_message = props.ref_message.clone();
    let show_message_callback = props.show_message_callback.clone();

    let dispatch = use_dispatch::<SessionListState>();
    let send_message_callback = Callback::from(move |_e| {
        log::info!("message send content000000000000: ");
        let content = get_textarea_value("messageEditorId");
        log::info!("message send content: {:?}, {:?}", content, session_clone);
        if content.is_none() {
            return;
        }

        if user_id_clone.is_none() || session_clone.is_none() {
            to_login(navigator.clone());
            return;
        }
        
        let session_clone2 = session_clone.clone().unwrap();
        let login_user_id = user_id_clone.clone().unwrap();

        let local_seq_value = local_seq(&login_user_id);
        log::info!("local seq: {}", local_seq_value);
        
        let user_id = login_user_id.clone();

        let app_state_clone2 = app_state_clone.clone();
        let ref_message_clone = ref_message.clone();
        let show_message_callback_clone = show_message_callback.clone();

        let dispatch_clone = dispatch.clone();
        spawn_local(async move {
            let message = MessageSendService::build_message(session_clone2.clone(), content.clone().unwrap(), ref_message_clone);
            let session_clone3 = session_clone2.clone();
            let mut session = session_clone3.borrow_mut();
            session.lately_message = content.clone().unwrap();
            session.update_time = Local::now();

            let mut messages = vec![message];

            remove_class("sendBtn", "send-btn");
            add_class("sendBtn", "send-btn-disabled");
            MessageSendService::send_message(app_state_clone2, vec![session.deref().clone()], &mut messages).await;
            show_message_callback_clone.emit(messages.clone());
            dispatch_clone.apply(SessionAction::UpdateSession(session.clone()));

            log::info!("send message success!!!!");
            set_textarea_value("messageEditorId", "");
            remove_class("sendBtn", "send-btn-disabled");
            add_class("sendBtn", "send-btn");
        });

    });

    html! {
        <div class="message-editor">
            <textarea id="messageEditorId" rows="3" class="message_editor"/>
            <div class="send-button-pane">
                <button id="sendBtn" class="send-btn" onclick={send_message_callback}> {"发 送"} </button>
            </div>
        </div>
    }
}